<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格渲染数据 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 根据mg_state的值判断开关是否打开 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- scope.row获取当前行中的所有数据 -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeGai(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              :id="scope"
              type="primary"
              icon="el-icon-edit"
              size="mini"
              round
              @click="modify"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              round
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                round
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 7, 9]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
        @close="addCz"
      >
        <!-- 内容主题区域 -->
        <el-form :model="add" :rules="addRules" ref="addRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="add.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="add.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="add.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="add.mobile"></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部按钮区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addTj">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    // 验证手机号的规则
    var checkmobile = (rule, value, cb) => {
      // 验证手机号的正则
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      // 如果符合规则返回
      if (regMobile.test(value)) return cb();
      // 不符合规则返回错误对象
      cb(new Error("请输入正确的手机号"));
    };
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      // 添加用户的对话框是否显示
      dialogVisible: false,
      // 添加用户的表单数据
      add: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加表单的验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkmobile, trigger: "blur" },
        ],
      },
      // 修改用户的对话框是否显示
      modlogVisible: false,
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户信息
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      // 获取用户信息失败
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      // 将获取到的数据存起来
      this.userlist = res.data.users;
      // 一共多少条数据
      this.total = res.data.total;
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听页码值发生改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 当状态发生改变触发事件
    async changeGai(changeZhi) {
      const { data: res } = await this.$http.put(
        `users/${changeZhi.id}/state/${changeZhi.mg_state}`
      );
      if (res.meta.status != 200) {
        changeZhi.mg_state = !changeZhi.mg_state;
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
    },
    // 添加用户的输入框关闭后触发
    addCz() {
      // 重置表单内的数据
      this.$refs.addRef.resetFields();
    },
    // 添加用户信息预验证
    addTj() {
      this.$refs.addRef.validate(async (val) => {
        if (!val) return;
        // 添加新用户
        const { data: res } = await this.$http.post("users", this.add);
        // 添加失败
        if (res.meta.status != 201) return this.$message.error(res.meta.msg);
        // 添加成功
        this.$message.error(res.meta.msg);
        // 渲染页面
        this.getUserList();
        // 关闭提示框.
        this.dialogVisible = false;
      });
    },
  },
};
</script>

<style lang="less" scoped>
</style>